import 'package:zhibao_flutter/util/check/option.dart';
import 'package:intl/intl.dart';

class MyDate {
  static String full = "yyyy-MM-dd HH:mm:ss";

  static int secondToLimit(second) {
    int _second;
    if (second == null) {
      return 0;
    } else if (second is int) {
      _second = second;
    } else {
      _second = int.parse(second.toString());
    }
    return int.parse(stringDisposeWithDouble(_second ~/ 60));
  }

  static String formatDateV(DateTime dateTime, {bool? isUtc, String? format}) {
    if (dateTime == null) return "";
    format = format ?? full;
    if (format.contains("yy")) {
      String year = dateTime.year.toString();
      if (format.contains("yyyy")) {
        format = format.replaceAll("yyyy", year);
      } else {
        format = format.replaceAll(
            "yy", year.substring(year.length - 2, year.length));
      }
    }

    format = _comFormat(dateTime.month, format, 'M', 'MM');
    format = _comFormat(dateTime.day, format, 'd', 'dd');
    format = _comFormat(dateTime.hour, format, 'H', 'HH');
    format = _comFormat(dateTime.minute, format, 'm', 'mm');
    format = _comFormat(dateTime.second, format, 's', 'ss');
    format = _comFormat(dateTime.millisecond, format, 'S', 'SSS');

    return format;
  }

  static String _comFormat(
      int value, String format, String single, String full) {
    if (format.contains(single)) {
      if (format.contains(full)) {
        format =
            format.replaceAll(full, value < 10 ? '0$value' : value.toString());
      } else {
        format = format.replaceAll(single, value.toString());
      }
    }
    return format;
  }

  static String formatTimeStampParse(timestamp, [String? format]) {
    assert(timestamp != null);
    DateTime dt = DateTime.parse("$timestamp");
    return formatTimeStampToString(dt.millisecondsSinceEpoch ~/ 1000, format);
  }

  /*
   * 时间格式转换
   * @param timestamp
   * @param format format yyyy-MM-dd HH:mm:ss
   *
   * */
  static String formatTimeStampToString(timestamp, [String? format]) {
    assert(timestamp != null);

    int time = 0;

    if (timestamp is int) {
      time = timestamp;
    } else {
      time = int.parse(timestamp.toString());
    }

    format ??= 'yyyy-MM-dd HH:mm:ss';

    DateFormat dateFormat = DateFormat(format);

    var date = DateTime.fromMillisecondsSinceEpoch(time * 1000);

    return dateFormat.format(date);
  }

  /*
  * 时间显示：
  *
  *（1）一小时内，显示为xx分钟前
  *（2） 小于24小时，显示为xx小时前
  *（3） 间隔超过24小时，显示：昨天xx：xx
  *（4） 间隔超过48小时，显示：xx月xx日 xx：xx
  *（5） 间隔超过一年，显示：xxxx年xx月xx日 xx：xx
  *
  * */
  static String recentTime(int? time) {
    if (time == null || time <= 0) {
      return '未知';
    }

    DateTime now = DateTime.now();
    DateTime publishTime = DateTime.fromMillisecondsSinceEpoch(time * 1000);
    Duration def = now.difference(publishTime);
    String _dtStr = MyDate.formatTimeStampToString(time, 'yyyy年MM月dd日 HH:mm');

    if (def.inDays > 365) {
      return _dtStr;
    } else if (def.inHours >= 48) {
      String _dtStr = MyDate.formatTimeStampToString(time, 'MM月dd日 HH:mm');
      return _dtStr;
    } else if (def.inDays >= 1 || def.inHours >= 24) {
      String _dtStr = MyDate.formatTimeStampToString(time, 'HH:mm');
      return '昨天$_dtStr';
    } else if (def.inHours <= 1 || def.inMinutes <= 60) {
      return '${def.inMinutes}分钟前';
    } else if (def.inHours <= 24 || def.inDays == 0) {
      return '${def.inHours}小时前';
    } else {
      return _dtStr;
    }
  }

  /// Chat time format.
  ///
  /// Use ["yyyy/MM/dd HH:mm:ss"]
  static String recentTimeInChatTime(int? time) {
    if (time == null || time <= 0) {
      return '未知';
    }

    /// 今天日期实体
    DateTime now = DateTime.now();

    /// 昨天日期实体
    DateTime yesterday = DateTime.now().subtract(Duration(days: 1));

    /// 数据时间实体
    DateTime publishTime = DateTime.fromMillisecondsSinceEpoch(time * 1000);

    /// 格式化之后的日期显示文本；显示例子（2022/11/02 22:12）
    String _dtStr = MyDate.formatTimeStampToString(time, 'yyyy/MM/dd HH:mm');

    /// 年份不相等，直接显示（yyyy/MM/dd HH:mm）
    if (now.year != publishTime.year) {
      return _dtStr;

      /// 同年同月同日，直接显示简短时间（HH:mm）
    } else if (now.month == publishTime.month && now.day == publishTime.day) {
      String _dtStr = MyDate.formatTimeStampToString(time, 'HH:mm');
      return _dtStr;

      /// 同月但不同日，且等于昨天的日
    } else if (now.month == publishTime.month &&
        now.day != publishTime.day &&
        publishTime.day == yesterday.day) {
      String _dtStr = MyDate.formatTimeStampToString(time, 'HH:mm');
      return '昨天$_dtStr';

      /// 否则就直接显示月份和日，例子（12/01 11:06）
    } else {
      String _dtStr = MyDate.formatTimeStampToString(time, 'MM/dd HH:mm');
      return _dtStr;
    }
  }

  /*
  * 时间显示：聊天专用
  *
  *（1）今天，正常显示时间，如："00:22"
  * (2) 昨天，显示："昨天 21:22"
  * (3) 本星期内，显示具体星期："星期五"【暂时不做】
  * (3) 超过一个星期，显示月份和日："3月27日"
  * (4) 去年："2021年2月18日"
  *
  * */
  static String recentTimeOfChat(int? time) {
    if (time == null || time <= 0) {
      return '未知';
    }

    DateTime now = DateTime.now();
    DateTime publishTime = DateTime.fromMillisecondsSinceEpoch(time * 1000);
    Duration def = now.difference(publishTime);

    if (def.inDays > 365) {
      return MyDate.formatTimeStampToString(time, 'yyyy年MM月dd日');
    } else if (def.inDays > 7) {
      return MyDate.formatTimeStampToString(time, 'MM月dd日');
    } else if (def.inDays == 1) {
      String _dtStr = MyDate.formatTimeStampToString(time, 'HH:mm');
      return '昨天$_dtStr';
    } else {
      return MyDate.formatTimeStampToString(time, 'HH:mm');
    }
  }

  /*
  * 获取最近时间
  *
  * */
  static String recentTimeOld(int time) {
    if (time == null || time <= 0) {
      return '未知';
    }
    DateTime now = DateTime.now();
    DateTime publishTime = DateTime.fromMillisecondsSinceEpoch(time * 1000);
    Duration def = now.difference(publishTime);
    String _strTotal = MyDate.formatTimeStampToString(time, 'MM-dd HH:mm:ss');
    // String _strEnd = MyDate.formatTimeStampToString(time, 'HH:mm');
    if (def.inDays < 1 && def.inHours > 1) {
      return '${def.inHours}小时前';
    } else if (def.inDays == 1) {
      return '${def.inHours + 24}小时前';
      // return '昨天 $_strEnd';
    } else if (def.inDays > 1 && def.inDays < 7) {
      return '${def.inDays}天前';
    } else if (def.inDays == 7) {
      return '一周前';
    } else if (def.inDays == 14) {
      return '两周前';
    } else if (def.inDays == 21) {
      return '三周前';
    } else if (def.inDays == 30) {
      return '一个月前';
    } else if (def.inDays == 60) {
      return '两个月前';
    } else {
      return _strTotal;
    }
  }

  /*
  * 算出每天的12月分别有多少天
  *
  * */
  static List<int> getDays([currentYear]) {
    List<int> days = [];
    for (int month = 1; month <= 12; month++) {
      var year = currentYear ?? DateTime.now().year;
      var dayCount = DateTime(year, month + 1, 0).day;
      days.add(dayCount);
    }
    return days;
  }
}

String toDate(dateTime) {
  return MyDate.formatTimeStampToString(
      dateTime.millisecondsSinceEpoch ~/ 1000);
}
